{{template "base" .}}
{{define "content"}}
<div x-data="permissionManager()" x-init="init()">
    <!-- 页面标题 -->
    <div class="mb-6">
        <div class="flex items-center justify-between">
            <div>
                <h1 class="text-2xl font-bold text-gray-900">权限管理</h1>
                <p class="text-gray-600">管理系统权限分组、权限项目和角色权限分配</p>
            </div>
            <div class="flex space-x-3">
                <button @click="showCreateModal()" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 flex items-center">
                    <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
                    </svg>
                    添加权限
                </button>
                <button @click="refreshPermissions()" :disabled="refreshing" class="bg-gray-600 text-white px-4 py-2 rounded-lg hover:bg-gray-700 flex items-center disabled:opacity-50 disabled:cursor-not-allowed">
                    <svg class="w-5 h-5 mr-2" :class="{'animate-spin': refreshing}" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
                    </svg>
                    <span x-text="refreshing ? '刷新中' : '刷新'"></span>
                </button>
            </div>
        </div>
    </div>

    <!-- 统计卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
        <div class="bg-white rounded-lg shadow-sm p-6">
            <div class="flex items-center">
                <div class="flex-shrink-0">
                    <div class="w-8 h-8 bg-blue-500 rounded-md flex items-center justify-center">
                        <svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"></path>
                        </svg>
                    </div>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-500">权限分组</p>
                    <p class="text-2xl font-semibold text-gray-900" x-text="stats.groups || 0"></p>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-lg shadow-sm p-6">
            <div class="flex items-center">
                <div class="flex-shrink-0">
                    <div class="w-8 h-8 bg-green-500 rounded-md flex items-center justify-center">
                        <svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"></path>
                        </svg>
                    </div>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-500">子权限</p>
                    <p class="text-2xl font-semibold text-gray-900" x-text="stats.permissions || 0"></p>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-lg shadow-sm p-6">
            <div class="flex items-center">
                <div class="flex-shrink-0">
                    <div class="w-8 h-8 bg-purple-500 rounded-md flex items-center justify-center">
                        <svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197m13.5-9a2.5 2.5 0 11-5 0 2.5 2.5 0 015 0z"></path>
                        </svg>
                    </div>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-500">关联角色</p>
                    <p class="text-2xl font-semibold text-gray-900" x-text="stats.total || 0"></p>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-lg shadow-sm p-6">
            <div class="flex items-center">
                <div class="flex-shrink-0">
                    <div class="w-8 h-8 bg-orange-500 rounded-md flex items-center justify-center">
                        <svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"></path>
                        </svg>
                    </div>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-500">权限分配</p>
                    <p class="text-2xl font-semibold text-gray-900" x-text="permissionGroups.length || 0"></p>
                </div>
            </div>
        </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="bg-white rounded-lg shadow-sm p-6 mb-6">
        <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
            <div class="flex flex-col sm:flex-row gap-4">
                <!-- 搜索框 -->
                <div class="relative">
                    <input type="text" 
                           x-model="searchQuery" 
                           @input="searchPermissions()" 
                           placeholder="搜索权限名称、显示名称、描述..." 
                           class="pl-10 pr-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 w-full sm:w-80">
                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                        <svg class="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                        </svg>
                    </div>
                </div>
                
                <!-- 类型筛选 -->
                <select x-model="typeFilter" @change="filterPermissions()" class="border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500">
                    <option value="">全部类型</option>
                    <option value="group">权限分组</option>
                    <option value="permission">子权限</option>
                </select>
                
                <!-- 资源筛选 -->
                <select x-model="resourceFilter" @change="filterPermissions()" class="border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500">
                    <option value="">全部资源</option>
                    <template x-for="resource in resources" :key="resource">
                        <option :value="resource" x-text="resource"></option>
                    </template>
                </select>
            </div>
            
        </div>
    </div>

    <!-- 权限列表 -->
    <div class="bg-white rounded-lg shadow-sm overflow-hidden">

        <!-- 批量操作栏 -->
        <div x-show="selectedPermissions.length > 0" class="bg-blue-50 border-b border-blue-200 px-6 py-3">
            <div class="flex items-center justify-between">
                <div class="flex items-center">
                    <span class="text-sm text-blue-700">已选择 <span x-text="selectedPermissions.length"></span> 个权限</span>
                </div>
                <div class="flex space-x-2">
                    <button @click="batchActivatePermissions()" :disabled="selectedPermissions.length === 0" class="bg-green-600 text-white px-3 py-1 rounded text-sm hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed">
                        批量激活
                    </button>
                    <button @click="batchDeactivatePermissions()" :disabled="selectedPermissions.length === 0" class="bg-yellow-600 text-white px-3 py-1 rounded text-sm hover:bg-yellow-700 disabled:opacity-50 disabled:cursor-not-allowed">
                        批量停用
                    </button>
                    <button @click="batchDeletePermissions()" :disabled="selectedPermissions.length === 0" class="bg-red-600 text-white px-3 py-1 rounded text-sm hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed">
                        批量删除
                    </button>
                    <button @click="selectedPermissions = []" class="bg-gray-600 text-white px-3 py-1 rounded text-sm hover:bg-gray-700">
                        取消选择
                    </button>
                </div>
            </div>
        </div>

        <!-- 表格头部 -->
        <div class="px-6 py-4 border-b border-gray-200">
            <div class="flex items-center justify-between">
                <div class="flex items-center">
                    <input type="checkbox" @change="toggleSelectAll()" :checked="isAllSelected()" class="rounded border-gray-300 text-blue-600 focus:ring-blue-500 mr-3">
                    <h3 class="text-lg font-medium text-gray-900">权限列表</h3>
                </div>
                <div class="text-sm text-gray-500">
                    共 <span x-text="pagination.total"></span> 个权限项
                </div>
            </div>
        </div>
        
        
        <!-- Loading状态 -->
        <div x-show="loading" class="flex justify-center items-center py-12">
            <div class="text-center">
                <svg class="animate-spin w-10 h-10 text-blue-500 mb-4 mx-auto" fill="none" viewBox="0 0 24 24">
                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
                <p class="text-gray-600">加载中...</p>
            </div>
        </div>
        
        <!-- 空状态 -->
        <div x-show="!loading && permissionGroups.length === 0" class="flex flex-col items-center justify-center py-12">
            <div class="text-center">
                <svg class="w-16 h-16 text-gray-300 mb-4 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"></path>
                </svg>
                <h3 class="text-lg font-medium text-gray-900 mb-2">暂无权限数据</h3>
                <p class="text-gray-500 mb-6" x-text="searchQuery || typeFilter || resourceFilter ? '没有找到符合条件的权限，请尝试调整搜索条件' : '系统中还没有权限数据，请先创建权限分组和权限项'"></p>
                <div class="flex flex-col sm:flex-row gap-3 justify-center">
                    <!-- 清除筛选按钮 -->
                    <button x-show="searchQuery || typeFilter || resourceFilter" @click="clearFilters()" class="bg-gray-500 text-white px-6 py-2 rounded-lg hover:bg-gray-600 flex items-center justify-center">
                        <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                        </svg>
                        清除筛选
                    </button>
                    <!-- 创建权限按钮 -->
                    <button @click="showCreateModal()" class="bg-blue-600 text-white px-6 py-2 rounded-lg hover:bg-blue-700 flex items-center justify-center">
                        <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
                        </svg>
                        <span x-text="searchQuery || typeFilter || resourceFilter ? '创建权限' : '创建第一个权限'"></span>
                    </button>
                </div>
            </div>
        </div>
        
        <!-- 权限树形结构 -->
        <div x-show="!loading && permissionGroups.length > 0" class="divide-y divide-gray-200">
            <template x-for="group in permissionGroups" :key="group.id">
                <div class="p-6">
                    <!-- 权限分组 -->
                    <div class="flex items-center justify-between mb-4">
                        <div class="flex items-center">
                            <input x-show="group.id !== 'default'" type="checkbox" :value="group.id" x-model="selectedPermissions" class="rounded border-gray-300 text-blue-600 focus:ring-blue-500 mr-3">
                            <div x-show="group.id === 'default'" class="w-5 h-5 mr-3"></div>
                            <button @click="toggleGroup(group.id)" class="flex items-center text-lg font-medium text-gray-900 hover:text-blue-600">
                                <svg :class="expandedGroups.includes(group.id) ? '' : 'transform -rotate-90'" class="w-4 h-4 mr-2 transition-transform" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
                                </svg>
                                <svg class="w-5 h-5 mr-2 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"></path>
                                </svg>
                                <span x-text="group.display_name"></span>
                                <span class="ml-2 text-sm text-gray-500">(<span x-text="group.children ? group.children.length : 0"></span>)</span>
                            </button>
                        </div>
                        <div class="flex items-center space-x-2">
                            <span class="inline-flex px-2 py-1 text-xs font-semibold rounded-full" 
                                  :class="group.id === 'default' ? 'bg-orange-100 text-orange-800' : 'bg-blue-100 text-blue-800'"
                                  x-text="group.id === 'default' ? '虚拟分组' : '分组'"></span>
                            <template x-if="group.id !== 'default'">
                                <button @click="editPermission(group)" class="text-indigo-600 hover:text-indigo-900" title="编辑分组">
                                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
                                    </svg>
                                </button>
                            </template>
                            <button @click="addChildPermission(group)" class="text-green-600 hover:text-green-900" title="添加子权限">
                                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
                                </svg>
                            </button>
                            <template x-if="group.id !== 'default'">
                                <button @click="deletePermission(group)" class="text-red-600 hover:text-red-900" title="删除分组">
                                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                                    </svg>
                                </button>
                            </template>
                        </div>
                    </div>
                    
                    <!-- 分组描述 -->
                    <div x-show="group.description" class="ml-8 mb-4 text-sm text-gray-600" x-text="group.description"></div>
                    
                    <!-- 子权限列表 -->
                    <div x-show="expandedGroups.includes(group.id)" class="ml-8 space-y-3">
                        <template x-for="permission in group.children" :key="permission.id">
                            <div class="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
                                <div class="flex items-center">
                                    <input type="checkbox" :value="permission.id" x-model="selectedPermissions" class="rounded border-gray-300 text-blue-600 focus:ring-blue-500 mr-3">
                                    <div class="flex items-center">
                                        <svg class="w-5 h-5 mr-2 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"></path>
                                        </svg>
                                        <div>
                                            <div class="font-medium text-gray-900" x-text="permission.display_name"></div>
                                            <div class="text-sm text-gray-500">
                                                <span x-text="permission.name"></span>
                                                <span x-show="permission.resource && permission.action" class="ml-2">
                                                    (<span x-text="permission.resource"></span>.<span x-text="permission.action"></span>)
                                                </span>
                                            </div>
                                            <div x-show="permission.description" class="text-sm text-gray-600 mt-1" x-text="permission.description"></div>
                                        </div>
                                    </div>
                                </div>
                                <div class="flex items-center space-x-2">
                                    <span class="inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-green-100 text-green-800">权限</span>
                                    <button @click="editPermission(permission)" class="text-indigo-600 hover:text-indigo-900" title="编辑权限">
                                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
                                        </svg>
                                    </button>
                                    <button @click="deletePermission(permission)" class="text-red-600 hover:text-red-900" title="删除权限">
                                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                                        </svg>
                                    </button>
                                </div>
                            </div>
                        </template>
                        
                        <!-- 空状态 -->
                        <div x-show="!group.children || group.children.length === 0" class="p-4 bg-gray-50 rounded-lg text-center text-gray-500">
                            <svg class="w-10 h-10 text-gray-400 mb-2 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4"></path>
                            </svg>
                            <p>该分组下暂无权限项</p>
                            <button @click="addChildPermission(group)" class="mt-2 text-blue-600 hover:text-blue-800 flex items-center justify-center">
                                <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
                                </svg>添加权限
                            </button>
                        </div>
                    </div>
                </div>
            </template>
        </div>
    </div>

    <!-- 创建/编辑权限模态框 -->
    <div x-show="showPermissionModal" 
         x-transition:enter="transition ease-out duration-300"
         x-transition:enter-start="opacity-0"
         x-transition:enter-end="opacity-100"
         x-transition:leave="transition ease-in duration-200"
         x-transition:leave-start="opacity-100"
         x-transition:leave-end="opacity-0"
         class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
        <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
            <div class="mt-3">
                <h3 class="text-lg font-medium text-gray-900 mb-4" x-text="permissionForm.id ? '编辑权限' : '创建权限'"></h3>
                
                <form @submit.prevent="savePermission()">
                    <!-- 权限类型 -->
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">权限类型</label>
                        <div class="flex space-x-4">
                            <label class="flex items-center">
                                <input type="radio" x-model="permissionForm.is_group" :value="true" class="mr-2">
                                <span>权限分组</span>
                            </label>
                            <label class="flex items-center">
                                <input type="radio" x-model="permissionForm.is_group" :value="false" class="mr-2">
                                <span>子权限</span>
                            </label>
                        </div>
                    </div>
                    
                    <!-- 父级分组 -->
                    <div x-show="!permissionForm.is_group" class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">父级分组</label>
                        <select x-model="permissionForm.pid" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500">
                            <option value="0">顶级分组</option>
                            <template x-for="group in permissionGroups" :key="group.id">
                                <option :value="group.id" x-text="group.display_name"></option>
                            </template>
                        </select>
                    </div>
                    
                    <!-- 权限名称 -->
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">权限名称</label>
                        <input type="text" x-model="permissionForm.name" required 
                               class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500"
                               placeholder="如：user.view">
                    </div>
                    
                    <!-- 显示名称 -->
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">显示名称</label>
                        <input type="text" x-model="permissionForm.display_name" required 
                               class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500"
                               placeholder="如：查看用户">
                    </div>
                    
                    <!-- 资源和操作 (仅子权限) -->
                    <div x-show="!permissionForm.is_group" class="grid grid-cols-2 gap-4 mb-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">资源</label>
                            <input type="text" x-model="permissionForm.resource" 
                                   class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500"
                                   placeholder="如：user">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">操作</label>
                            <input type="text" x-model="permissionForm.action" 
                                   class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500"
                                   placeholder="如：view">
                        </div>
                    </div>
                    
                    <!-- 描述 -->
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">描述</label>
                        <textarea x-model="permissionForm.description" rows="3" 
                                  class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500"
                                  placeholder="权限描述信息"></textarea>
                    </div>
                    
                    <!-- 排序 -->
                    <div class="mb-6">
                        <label class="block text-sm font-medium text-gray-700 mb-2">排序</label>
                        <input type="number" x-model="permissionForm.sort" 
                               class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500"
                               placeholder="数字越小越靠前">
                    </div>
                    
                    <!-- 按钮 -->
                    <div class="flex justify-end space-x-3">
                        <button type="button" @click="showPermissionModal = false" 
                                class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50">
                            取消
                        </button>
                        <button type="submit" 
                                class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
                            保存
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
function permissionManager() {
    return {
        // 数据状态
        permissions: [],
        permissionGroups: [],
        resources: [],
        stats: {
            total: 0,
            groups: 0,
            permissions: 0
        },
        initialized: false,
        refreshing: false,
        searchTimer: null,
        
        // 搜索和筛选
        searchQuery: '',
        typeFilter: '',
        resourceFilter: '',
        
        // 选择状态
        selectedPermissions: [],
        expandedGroups: [],
        
        // 分页
        pagination: {
            page: 1,
            limit: 20,
            total: 0
        },
        
        // 模态框状态
        showPermissionModal: false,
        
        // 加载状态
        loading: false,
        
        // 表单数据
        permissionForm: {
            id: null,
            pid: 0,
            name: '',
            display_name: '',
            resource: '',
            action: '',
            description: '',
            sort: 0,
            is_group: true
        },
        
        // 初始化
        async init() {
            if (this.initialized || this.loading) {
                return;
            }
            this.loading = true;
            this.initialized = true;
            
            try {
                await Promise.all([
                    this.loadStats(),
                    this.loadPermissions(),
                    this.loadResources()
                ]);
            } catch (error) {
                console.error('初始化失败:', error);
                this.showToast('初始化失败，请刷新页面重试', 'error');
            } finally {
                this.loading = false;
            }
        },
        
        // 加载统计数据
        async loadStats() {
            try {
                const response = await fetch('/api/v1/system/permissions/stats');
                const result = await response.json();
                if (result.code === 200) {
                    this.stats = {
                        total: result.data.total || 0,
                        groups: result.data.groups || 0,
                        permissions: result.data.permissions || 0
                    };
                } else {
                    console.error('统计数据API返回错误:', result);
                }
            } catch (error) {
                console.error('加载统计数据失败:', error);
            }
        },
        
        // 加载权限列表
        async loadPermissions() {
            this.loading = true;
            try {
                const params = new URLSearchParams({
                    page: this.pagination.page,
                    limit: this.pagination.limit,
                    search: this.searchQuery,
                    type: this.typeFilter,
                    resource: this.resourceFilter
                });
                
                const response = await fetch(`/api/v1/system/permissions?${params}`);
                const result = await response.json();
                
                if (result.code === 200) {
                    const permissions = result.data.permissions || [];
                    
                    // 分离权限分组和具体权限
                    const groups = permissions.filter(p => p.is_group);
                    const specificPermissions = permissions.filter(p => !p.is_group);
                    
                    // 为每个分组添加子权限
                    this.permissionGroups = groups.map(group => {
                        const children = specificPermissions.filter(p => p.pid === group.id);
                        return {
                            ...group,
                            children: children
                        };
                    });
                    
                    // 如果没有分组，创建一个默认分组显示所有权限
                    if (groups.length === 0 && specificPermissions.length > 0) {
                        // 找出没有父级的权限（pid为0或父级不存在的权限）
                        const orphanPermissions = specificPermissions.filter(p => {
                            return p.pid === 0 || !permissions.find(parent => parent.id === p.pid);
                        });
                        
                        if (orphanPermissions.length > 0) {
                            this.permissionGroups = [{
                                id: 'default',
                                name: 'default_group',
                                display_name: '未分组权限',
                                description: '系统中未归类的权限项',
                                is_group: true,
                                children: orphanPermissions
                            }];
                        }
                    }
                    
                    this.permissions = specificPermissions;
                    this.pagination.total = result.data.total || 0;
                    
                    // 默认展开所有分组
                    this.expandedGroups = this.permissionGroups.map(group => group.id);
                } else {
                    console.error('权限API返回错误:', result);
                    this.showToast('加载权限列表失败: ' + (result.message || '未知错误'), 'error');
                }
            } catch (error) {
                console.error('加载权限列表失败:', error);
                this.showToast('加载权限列表失败', 'error');
            } finally {
                this.loading = false;
            }
        },
        
        // 加载资源列表
        async loadResources() {
            try {
                const response = await fetch('/api/v1/system/permissions/resources');
                const result = await response.json();
                if (result.code === 200) {
                    this.resources = result.data || [];
                } else {
                    console.error('资源API返回错误:', result);
                }
            } catch (error) {
                console.error('加载资源列表失败:', error);
            }
        },
        
        // 搜索权限
        searchPermissions() {
            if (this.searchTimer) {
                clearTimeout(this.searchTimer);
            }
            this.searchTimer = setTimeout(() => {
                this.pagination.page = 1;
                this.loadPermissions();
            }, 300);
        },
        
        // 筛选权限
        filterPermissions() {
            this.pagination.page = 1;
            this.loadPermissions();
        },
        
        // 清除筛选条件
        clearFilters() {
            this.searchQuery = '';
            this.typeFilter = '';
            this.resourceFilter = '';
            this.pagination.page = 1;
            this.loadPermissions();
        },
        
        // 刷新权限列表
        async refreshPermissions() {
            if (this.refreshing) {
                return;
            }
            
            this.refreshing = true;
            
            try {
                await Promise.all([
                    this.loadStats(),
                    this.loadPermissions()
                ]);
            } catch (error) {
                console.error('刷新失败:', error);
            } finally {
                this.refreshing = false;
            }
        },
        
        // 切换分组展开/收起
        toggleGroup(groupId) {
            const index = this.expandedGroups.indexOf(groupId);
            if (index > -1) {
                this.expandedGroups.splice(index, 1);
            } else {
                this.expandedGroups.push(groupId);
            }
        },
        
        // 显示创建模态框
        showCreateModal() {
            this.permissionForm = {
                id: null,
                pid: 0,
                name: '',
                display_name: '',
                resource: '',
                action: '',
                description: '',
                sort: 0,
                is_group: true
            };
            this.showPermissionModal = true;
        },
        
        // 编辑权限
        editPermission(permission) {
            this.permissionForm = {
                id: permission.id,
                pid: permission.pid || 0,
                name: permission.name,
                display_name: permission.display_name,
                resource: permission.resource || '',
                action: permission.action || '',
                description: permission.description || '',
                sort: permission.sort || 0,
                is_group: permission.is_group
            };
            this.showPermissionModal = true;
        },
        
        // 添加子权限
        addChildPermission(parentGroup) {
            this.permissionForm = {
                id: null,
                pid: parentGroup.id,
                name: '',
                display_name: '',
                resource: '',
                action: '',
                description: '',
                sort: 0,
                is_group: false
            };
            this.showPermissionModal = true;
        },
        
        // 保存权限
        async savePermission() {
            try {
                const url = this.permissionForm.id 
                    ? `/api/v1/system/permissions/${this.permissionForm.id}` 
                    : '/api/v1/system/permissions';
                const method = this.permissionForm.id ? 'PUT' : 'POST';
                
                const response = await fetch(url, {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(this.permissionForm)
                });
                
                const result = await response.json();
                
                if (result.code === 200) {
                    this.showToast(this.permissionForm.id ? '权限更新成功' : '权限创建成功', 'success');
                    this.showPermissionModal = false;
                    await this.refreshPermissions();
                } else {
                    this.showToast(result.message || '保存失败', 'error');
                }
            } catch (error) {
                this.showToast('保存失败', 'error');
            }
        },
        
        // 删除权限
        async deletePermission(permission) {
            const isGroup = permission.is_group;
            const hasChildren = isGroup && permission.children && permission.children.length > 0;
            
            let confirmMessage = `确定要删除${isGroup ? '分组' : '权限'} "${permission.display_name}" 吗？`;
            if (hasChildren) {
                confirmMessage += `\n该分组下有 ${permission.children.length} 个子权限，删除后将一并删除！`;
            }
            
            if (confirm(confirmMessage)) {
                try {
                    const response = await fetch(`/api/v1/system/permissions/${permission.id}`, {
                        method: 'DELETE'
                    });
                    const result = await response.json();
                    
                    if (result.code === 200) {
                        this.showToast('删除成功', 'success');
                        await this.refreshPermissions();
                    } else {
                        this.showToast(result.message || '删除失败', 'error');
                    }
                } catch (error) {
                    this.showToast('删除失败', 'error');
                }
            }
        },
        
        // 批量删除权限
        async batchDeletePermissions() {
            if (this.selectedPermissions.length === 0) {
                this.showToast('请选择要删除的权限', 'warning');
                return;
            }
            
            if (confirm(`确定要删除选中的 ${this.selectedPermissions.length} 个权限吗？此操作不可恢复！`)) {
                try {
                    const response = await fetch('/api/v1/system/permissions/batch-delete', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            permission_ids: this.selectedPermissions
                        })
                    });
                    
                    const result = await response.json();
                    
                    if (result.code === 200) {
                        this.showToast('批量删除成功', 'success');
                        this.selectedPermissions = [];
                        await this.refreshPermissions();
                    } else {
                        this.showToast(result.message || '批量删除失败', 'error');
                    }
                } catch (error) {
                    this.showToast('批量删除失败', 'error');
                }
            }
        },
        
        // 全选/取消全选
        toggleSelectAll() {
            if (this.isAllSelected()) {
                this.selectedPermissions = [];
            } else {
                // 收集所有可选择的权限ID（排除default分组）
                const allPermissionIds = [];
                this.permissionGroups.forEach(group => {
                    if (group.id !== 'default') {
                        allPermissionIds.push(group.id);
                    }
                    if (group.children) {
                        group.children.forEach(permission => {
                            allPermissionIds.push(permission.id);
                        });
                    }
                });
                this.selectedPermissions = allPermissionIds;
            }
        },
        
        // 检查是否全选
        isAllSelected() {
            // 计算所有可选择的权限数量（排除default分组）
            let totalSelectablePermissions = 0;
            this.permissionGroups.forEach(group => {
                if (group.id !== 'default') {
                    totalSelectablePermissions++;
                }
                if (group.children) {
                    totalSelectablePermissions += group.children.length;
                }
            });
            return totalSelectablePermissions > 0 && this.selectedPermissions.length === totalSelectablePermissions;
        },
        
        // 批量激活权限
        async batchActivatePermissions() {
            if (this.selectedPermissions.length === 0) return;
            
            if (!confirm(`确定要激活选中的 ${this.selectedPermissions.length} 个权限吗？`)) return;
            
            try {
                const response = await fetch('/api/v1/system/permissions/batch-activate', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        permission_ids: this.selectedPermissions
                    })
                });
                
                const result = await response.json();
                
                if (result.code === 200) {
                    this.showToast('批量激活成功', 'success');
                    this.selectedPermissions = [];
                    await this.refreshPermissions();
                } else {
                    this.showToast(result.message, 'error');
                }
            } catch (error) {
                this.showToast('批量激活失败', 'error');
            }
        },
        
        // 批量停用权限
        async batchDeactivatePermissions() {
            if (this.selectedPermissions.length === 0) return;
            
            if (!confirm(`确定要停用选中的 ${this.selectedPermissions.length} 个权限吗？`)) return;
            
            try {
                const response = await fetch('/api/v1/system/permissions/batch-deactivate', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        permission_ids: this.selectedPermissions
                    })
                });
                
                const result = await response.json();
                
                if (result.code === 200) {
                    this.showToast('批量停用成功', 'success');
                    this.selectedPermissions = [];
                    await this.refreshPermissions();
                } else {
                    this.showToast(result.message, 'error');
                }
            } catch (error) {
                this.showToast('批量停用失败', 'error');
            }
        },
        
        // 工具函数
        showToast(message, type = 'info') {
            // 这里可以集成一个 toast 组件
            console.log(`${type}: ${message}`);
            alert(message);
        }
    };
}
</script>
{{end}}